package com.example.myprojectoffeixue;

/**
 * Created by ASUS on 2016/11/18.
 */
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.InputFilter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import org.apache.http.entity.StringEntity;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author IdeasAndroid
 *         可展开（收缩）列表示例
 */
public class IdeasExpandableListAdapter2 extends BaseExpandableListAdapter {
    Dialog dialog;
    private Context mContext = null;
    private MyApplication m;
    private List<GateWay> groupList;
    private List<List<SheBeiClass>> itemList ;
    PermissionsActivity st;
    EditText et;
    public String flag;
    public IdeasExpandableListAdapter2(Context context, List<GateWay>groupList,List<List<SheBeiClass>>itemList,String flag) {
        this.mContext = context;
        this.itemList=itemList;
        this.groupList=groupList;
        this.flag=flag;
        st= (PermissionsActivity) mContext;
        m= (MyApplication) st.getApplication();
    }

    /**
     * 初始化数据，将相关数据放到List中，方便处理
     */
    public boolean areAllItemsEnabled() {
        return false;
    }

    /*
     * 设置子节点对象，在事件处理时返回的对象，可存放一些数据
     */
    public Object getChild(int groupPosition, int childPosition) {
        return itemList.get(groupPosition).get(childPosition);
    }

    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    /*
     * 字节点视图，这里我们显示一个文本对象
     */
    public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        ViewHolder h = null;
        if (convertView == null) {
            h = new ViewHolder();
            LayoutInflater inflater = LayoutInflater.from(mContext);
            convertView = inflater.inflate(R.layout.item3, null);
            h.tv = (TextView) convertView.findViewById(R.id.tv_listview);
            convertView.setTag(h);
        } else {
            h = (ViewHolder) convertView.getTag();
        }
        // 获取子节点要显示的名称
        String name = itemList.get(groupPosition).get(childPosition).deviceName;
        // 设置文本视图的相关属性

        if (itemList.get(groupPosition).get(childPosition).deviceId != null) {
            if ("0100".equals(itemList.get(groupPosition).get(childPosition).deviceId)){
                //墙面三路开关
                if (name != null) {
                    h.tv.setText(name+"(墙面开关)");
                } else {
                    h.tv.setText("墙面开关");
                }


            } else if ("010B".equals(itemList.get(groupPosition).get(childPosition).deviceId)||"010A".equals(itemList.get(groupPosition).get(childPosition).deviceId)) {
                //智能门锁
                if (name != null) {
                    h.tv.setText(name+"(智能门锁)");
                } else {
                    h.tv.setText("智能门锁");
                }

            } else if ("010D".equals(itemList.get(groupPosition).get(childPosition).deviceId)) {
//门磁
                if (name != null) {
                    h.tv.setText(name+"(智能门磁)");
                } else {
                    h.tv.setText("智能门磁");
                }


            } else if ("010E".equals(itemList.get(groupPosition).get(childPosition).deviceId)) {
//红外
                if (name != null) {
                    h.tv.setText(name+"(智能红外)");
                } else {
                    h.tv.setText("智能红外");
                }

            } else if ("010C".equals(itemList.get(groupPosition).get(childPosition).deviceId)) {
//取电

                if (name != null) {
                    h.tv.setText(name+"(智能取电)");
                } else {
                    h.tv.setText("智能取电");
                }

            } else if ("0002".equals(itemList.get(groupPosition).get(childPosition).deviceId)) {

                if (name != null) {
                    h.tv.setText(name+"(智能窗帘)");
                } else {
                    h.tv.setText("智能窗帘");
                }


            } else if ("0009".equals(itemList.get(groupPosition).get(childPosition).deviceId)) {

                if (name != null) {
                    h.tv.setText(name+"(智能插座)");
                } else {
                    h.tv.setText("智能插座");
                }


            } else if ("0020".equals(itemList.get(groupPosition).get(childPosition).deviceId)) {
                if (name != null) {
                    h.tv.setText(name+"(红外转发器)");
                } else {
                    h.tv.setText("红外转发器");
                }


            }else if ("010F".equals(itemList.get(groupPosition).get(childPosition).deviceId)) {
                if (name != null) {
                    h.tv.setText(name+"(中央空调)");
                } else {
                    h.tv.setText("中央空调");
                }

            }

        }

        return convertView;
    }


    /*
     * 返回当前分组的字节点个数
     */
    public int getChildrenCount(int groupPosition) {
        return itemList.get(groupPosition).size();
    }

    /*
     * 返回分组对象，用于一些数据传递，在事件处理时可直接取得和分组相关的数据
     */
    public Object getGroup(int groupPosition) {
        return groupList.get(groupPosition);
    }

    /*
     * 分组的个数
     */
    public int getGroupCount() {
        return groupList.size();
    }

    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    /*
     * 分组视图，这里也是一个文本视图
     */
    public View getGroupView(final int groupPosition, final boolean isExpanded, View convertView, ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater inflater = LayoutInflater.from(mContext);
            convertView = inflater.inflate(R.layout.item2_premission, null);
        }
        convertView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
                public boolean onLongClick(View v) {

                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setTitle("是否删除权限？");
                builder.setIcon(android.R.drawable.ic_dialog_info);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                            GateWay Gw = new GateWay();
                            if (groupList.size() != 0) {
                                Gw.id = groupList.get(groupPosition).id;
                            }
                            String j = JSON.toJSONString(Gw);
                            Log.d("j", j);
                            j = AESUtil.encrypt(j);
                            Log.d("url", HttpConnection.deleteAuthMac);
                            HttpUtils httpUtils = new HttpUtils();
                            RequestParams paraMyappyapps = new RequestParams();

                            paraMyappyapps.setHeader("Content-Type", "application/json");
                            try {
                                paraMyappyapps.setBodyEntity(new StringEntity(j, "utf-8"));
                            } catch (UnsupportedEncodingException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            httpUtils.send(HttpRequest.HttpMethod.POST, HttpConnection.deleteAuthMac, paraMyappyapps,
                                    new RequestCallBack<String>() {
                                        @Override
                                        public void onFailure(HttpException arg0, String arg1) {
                                            HttpConnection.toastLog("网络异常", mContext);
                                        }

                                        @Override
                                        public void onSuccess(ResponseInfo<String> arg0) {
                                            Log.d("deleterrr","hhhhhhhhhhhhh");
                                            Log.d("delete",arg0.result);
                                            if (arg0.result != null && !("".equals(arg0.result))) {

                                                arg0.result = AESUtil.decrypt(arg0.result);
                                                Log.d("delete",arg0.result);
                                                JSONObject j = JSONObject.parseObject(arg0.result);
                                                Integer it = j.getInteger("status");
                                                if (0 == it) {
                                                    groupList.remove(groupPosition);
                                                    itemList.remove(groupPosition);
                                                     m.GetDeviceList();
                                                   IdeasExpandableListAdapter2.this.notifyDataSetChanged();
                                                }
                                            } else {

                                                HttpConnection.toastLog("服务器错误", mContext);

                                            }
                                        }
                                    });

                        }

                });
                builder.setNegativeButton("取消", null);
                AlertDialog dialog = builder.create();
                dialog.show();
                return false;
            }
        });

       convertView.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
              if(isExpanded){
               st.el.collapseGroup(groupPosition);}else{
                  st.el.expandGroup(groupPosition);

              }
           }
       });

        Log.d(groupPosition+"",groupList.get(groupPosition).id+"");
        ImageView iv = (ImageView) convertView.findViewById(R.id.tubiao);
        TextView text = (TextView) convertView.findViewById(R.id.content_001);
        TextView text2= (TextView) convertView.findViewById(R.id.delete);
        TextView mobile= (TextView) convertView.findViewById(R.id.mobile);

        text2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GateWay Gw = new GateWay();
                Gw.id = groupList.get(groupPosition).id;
                String j = JSON.toJSONString(Gw);
                Log.d("j", j);
                j = AESUtil.encrypt(j);
                Log.d("url", HttpConnection.deleteAuthMac);
                HttpUtils httpUtils = new HttpUtils();
                RequestParams paraMyappyapps = new RequestParams();

                paraMyappyapps.setHeader("Content-Type", "application/json");
                try {
                    paraMyappyapps.setBodyEntity(new StringEntity(j, "utf-8"));
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                httpUtils.send(HttpRequest.HttpMethod.POST, HttpConnection.confirmAuthMac, paraMyappyapps,
                        new RequestCallBack<String>() {
                            @Override
                            public void onFailure(HttpException arg0, String arg1) {
                                HttpConnection.toastLog("网络异常", mContext);
                            }

                            @Override
                            public void onSuccess(ResponseInfo<String> arg0) {
                                if (arg0.result != null && !("".equals(arg0.result))) {
                                    arg0.result = AESUtil.decrypt(arg0.result);
                                    JSONObject j = JSONObject.parseObject(arg0.result);
                                    Integer it = j.getInteger("status");
                                    if (0 == it) {
                                        groupList.get(groupPosition).status = 1;
                                        IdeasExpandableListAdapter2.this.notifyDataSetChanged();
                                        m.GetDeviceList();
                                    }else{
                                        HttpConnection.toastLog("服务器错误", mContext);
                                    }
                                } else {
                                    HttpConnection.toastLog("服务器错误", mContext);
                                }
                            }
                        });

            }
        });
        if (groupList.get(groupPosition).status == 0) {
            if(flag.equals("1")){
            text2.setText("未接受");}else{
                text2.setText("未同意");
            }
            text2.setBackgroundResource(R.drawable.bg_edittext_color);
        } else {
            if(flag.equals("1")){
                text2.setText("已接受");}else{
                text2.setText("已同意");
            }

            text2.setBackgroundResource(R.drawable.stop_gate);
        }


        if(flag.equals("1")){

            mobile.setText("来自："+groupList.get(groupPosition).mobileFrom);
        }else{
            mobile.setText("共享至："+groupList.get(groupPosition).mobileTo);
        }


         String name = (String) groupList.get(groupPosition).mac;
        if (name != null) {
            text.setText(name);
        } else {
            text.setText("墙面开关");
        }

        if (isExpanded) {
            iv.setImageResource(R.drawable.button_xiajiantou);

        } else {

            iv.setImageResource(R.drawable.button_youjiantou);

        }



        return convertView;
    }

    /*
     * 判断分组是否为空，本示例中数据是固定的，所以不会为空，我们返回false
     * 如果数据来自数据库，网络时，可以把判断逻辑写到这个方法中，如果为空
     * 时返回true
     */
    public boolean isEmpty() {
        return false;
    }

    /*
     * 收缩列表时要处理的东西都放这儿
     */
    public void onGroupCollapsed(int groupPosition) {

    }

    /*
     * 展开列表时要处理的东西都放这儿
     */
    public void onGroupExpanded(int groupPosition) {

    }

    /*
     * Indicates whether the child and group IDs are stable across changes to
     * the underlying data.
     */
    public boolean hasStableIds() {
        return false;
    }

    /*
     * Whether the child at the specified position is selectable.
     */
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }


    class ViewHolder {

        TextView tv;
        ImageView iv;
        ImageView iv1;


    }


}
